#define _CRT_SECURE_NO_WARNINGS
#include "stack.h"

void StackInit(Stack* ps)
{
	assert(ps);
	STDataType* tmp = (STDataType*)malloc(sizeof(STDataType) * 4);
	if (!tmp)
	{
		perror("create fail!");
		exit(-1);
	}
	ps->a = tmp;
	ps->capacity = sizeof(STDataType);
	ps->top = -1;
}


void StackPush(Stack* ps, STDataType data)
{
	assert(ps);
	if (ps->top + 1 == ps->capacity)
	{
		STDataType* tmp = (STDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(STDataType));
		if (!tmp)
		{
			perror("create fail!");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity *= 2;
	}
	ps->a[++ps->top] = data;
}

void StackPop(Stack* ps)
{
	assert(ps);
	assert(StackEmpty(ps));
	ps->top--;
}

STDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(StackEmpty(ps));
	return ps->a[ps->top];
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->top + 1;
}

int StackEmpty(Stack* ps)
{
	assert(ps);
	return ps->top == -1;
}


void StackDestroy(Stack* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = -1;
}